package com.snail.commonlibrary;

import android.content.Context;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;

/**
 * Http地址请求工具
 *
 * @author zhaoys
 */
public class RequestUtil {

    /**
     * 设置请求超时10秒钟
     */
    public int REQUEST_TIMEOUT = 10 * 1000;

    /**
     * xutils请求工具类
     */
    public static HttpUtils httpClient = new HttpUtils();
    /**
     * Url共用部分网址
     */
    public String urlAddress = "http://dt-clan.woniu.com/dt/app/";

    public RequestUtil() {
    }

    /**
     * @param purl    请求网址
     * @param pparams 请求网址参数
     * @param context
     */
    public RequestUtil(String purl, RequestParams pparams, Context context) {
        this.url = urlAddress + purl;
        this.params = pparams;
        this.activity = context;
    }

    /**
     * 请求地址
     */
    public String url;
    /**
     * 请求参数
     */
    public RequestParams params;
    /**
     * 记录在哪个界面中运行
     */
    public Context activity;

    /**
     * post请求
     */
    public void sendPost() {
        if (null == mc)
            System.out.print("回调函数(CallBackInterface mc)不能为空");
        //http为HttpUtils实例
        httpClient.configTimeout(REQUEST_TIMEOUT);
        httpClient.send(HttpRequest.HttpMethod.POST, url, params,
                new RequestCallBack<String>() {

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        mc.success(responseInfo.result);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        mc.failure(msg);
                    }
                });
    }

    /**
     * get请求
     */
    public void sendGet() {
        if (null == mc)
            System.out.print("回调函数(CallBackInterface mc)不能为空");
        httpClient.configTimeout(REQUEST_TIMEOUT);
        httpClient.send(HttpRequest.HttpMethod.GET, url,
                new RequestCallBack<String>() {
                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        mc.success(responseInfo.result);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        mc.failure(msg);
                    }
                });
    }

    private CallBackInterface mc;

    public void setCallfuc(CallBackInterface mc) {
        this.mc = mc;
    }
}
